const http = require("http");
const fs = require("fs");

function handleErr(err,res) {
    console.log(err);
    res.end('Server error');
}

function formatHtml(data, html, res) {
    res.writeHead(200, {"Content-Type":"text/html"});
    console.log(typeof (data));
    console.log(data);
    const listr = data.join('</li><li>');
    console.log(listr)
    res.end(html.replace('%', listr));
}

function getTemplate(data, res) {
    fs.readFile("./template.html",(err,html) => {
        if (err) {
            return handleErr(err,res);
        }
        formatHtml(data, html.toString(), res);
    })
}

function getTitles(res) {
    fs.readFile("./titles.json", (err,data) => {
        if (err) {
            return handleErr(err,res);
        }

        getTemplate(JSON.parse(data.toString()), res);

    });
}

http.createServer((req, res) => {
    getTitles(res);
}).listen(8000, "localhost",() =>{
    console.log("Server listen port : 8000")
});

